<template>
  <v-dialog-layout
    title="添加应用"
    width="500px"
    v-model:visible="visible"
    @confirm="formAdd.onSubmit()"
    @cancel="cancel"
  >
    <v-form-layout
      ref="formAdd"
      v-model:form-data="formData"
      :rules="rules"
      @validateSuccess="validateSuccess"
      @validateError="validateError"
    >
      <a-form-item label="应用名称" name="name" placeholder="请输入应用名称">
        <a-input v-model:value.trim="formData.name" />
      </a-form-item>
      <a-form-item label="应用编号" name="appCode" placeholder="请输入应用编号">
        <a-input v-model:value.trim="formData.appCode" />
      </a-form-item>
      <a-form-item label="应用路径" required name="baseUrl" placeholder="请输入应用路径">
        <a-input v-model:value.trim="formData.baseUrl" />
      </a-form-item>
      <a-form-item label="显示顺序" name="order" placeholder="请输入显示顺序">
        <a-input v-model:value.trim="formData.order" />
      </a-form-item>
      <a-form-item label="是否可用" name="enabled">
        <a-select v-model:value="formData.enabled" placeholder="请选择">
          <a-select-option :value="0">否</a-select-option>
          <a-select-option :value="1">是</a-select-option>
        </a-select>
      </a-form-item>
    </v-form-layout>
  </v-dialog-layout>
</template>

<script setup lang="ts">
import { addRules } from './config'
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import useCurrentInstance from 'lib-utils/vueInstance'

const { proxy } = useCurrentInstance()
const props = withDefaults(defineProps<{
  visible: boolean,
  initForm: any
}>(), {
  visible: false
})
const emit = defineEmits(['update:visible', 'close'])

let formAdd = ref();
const formData = reactive({
  id: '',
  name: '',
  appCode: '',
  order: null,
  baseUrl: '',
  enabled: 1
});
const rules = addRules

onMounted(() => {
  if (props.initForm) {
    for (let item in formData) {
      formData[item] = props.initForm[item]
    }
    if (formData.enabled) {
      formData.enabled = 1
    } else {
      formData.enabled = 0
    }
    formData.id = props.initForm['id']
  }
})

const validateSuccess = () => {
  if (formData.id) {
    proxy.$http.post(proxy.$api.application.update, formData).then(res => {
      message.success('更新成功')
      emit('update:visible', false)
      emit('close', false)
    }).catch(err => {
    })
  } else {
    // delete formData['id'] TODO
    proxy.$http.post(proxy.$api.application.add, formData).then(res => {
      message.success('添加成功')
      emit('update:visible', false)
      emit('close', false)
    }).catch(err => {
    })
  }
};

const validateError = (e) => {
  message.error('校验失败')
};

const cancel = () => {
  emit('update:visible', false)
};
</script>

<style scoped>
</style>